package com.nandi.deviceinstall.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.nandi.deviceinstall.R
import com.nandi.deviceinstall.base.BaseMvpActivity
import com.nandi.deviceinstall.bean.BindRecordBean
import com.nandi.deviceinstall.bean.BindRecordInfoBean
import com.nandi.deviceinstall.bean.ListDataBean
import com.nandi.deviceinstall.common.Constant
import com.nandi.deviceinstall.contract.BindRecordInfoContract
import com.nandi.deviceinstall.presenter.BindRecordInfoPresenter
import com.nandi.deviceinstall.presenter.BindRecordPresenter
import com.nandi.deviceinstall.util.CustomToast
import com.nandi.deviceinstall.util.SharedTool
import com.nandi.deviceinstall.weight.imagepicker.*
import kotlinx.android.synthetic.main.activity_record_info.*
import kotlinx.android.synthetic.main.activity_record_info.data
import kotlinx.android.synthetic.main.activity_record_info.deviceFac
import kotlinx.android.synthetic.main.activity_record_info.deviceNum
import kotlinx.android.synthetic.main.activity_record_info.deviceType
import kotlinx.android.synthetic.main.activity_record_info.disasterName
import kotlinx.android.synthetic.main.activity_record_info.disasterNum
import kotlinx.android.synthetic.main.activity_record_info.district
import kotlinx.android.synthetic.main.activity_record_info.img_show
import kotlinx.android.synthetic.main.activity_record_info.installLoc
import kotlinx.android.synthetic.main.activity_record_info.lat_bind_1
import kotlinx.android.synthetic.main.activity_record_info.lon_bind_1
import kotlinx.android.synthetic.main.activity_record_info.monitorNum
import kotlinx.android.synthetic.main.activity_record_info.state
import kotlinx.android.synthetic.main.activity_record_info.township
import kotlinx.android.synthetic.main.dialog_tips.view.*
import kotlinx.android.synthetic.main.toolbar_back_include.*
import java.io.File
import java.io.Serializable
import java.util.ArrayList

class RecordInfoActivity : BaseMvpActivity<BindRecordInfoPresenter>(), BindRecordInfoContract.View {
    override fun handlerDataResult(t: ListDataBean) {
        if (t.data?.monitoringData?.isNotEmpty()!!) {
            val intent = Intent(this@RecordInfoActivity, DataShowActivity::class.java)
            intent.putExtra("data", t)
            startActivity(intent)
        } else {
            initTipsDialog("暂无监测数据")
        }
    }

    private val listDeviceType = arrayOf("地裂缝", "墙裂缝", "地面倾斜", "智能报警器", "雨量计", "泥位计")

    private val maxImgCount = 10000 // 最大选择图片数量
    private lateinit var adapter: ImagePickerNoAddAdapter
    internal var selImageList: MutableList<ImageItem> = ArrayList() //图片集合
    override val layoutId: Int
        get() = R.layout.activity_record_info

    private var id: Int = 0
    private lateinit var info: BindRecordBean.DataBean.RecordsBean
//    private lateinit var info: BindRecordInfoBean

    override fun initView() {
        mPresenter = BindRecordInfoPresenter()
        mPresenter.attachView(this)
        tv_title_toolbar.text = "绑点详情"

        title_image.setImageResource(R.drawable.xiugai)
        right_tv.setText("修改")
        val extras = intent.extras
        info = extras.getSerializable("item") as BindRecordBean.DataBean.RecordsBean
        initImagePicker()
//        mPresenter.requestBindRecordInfo(SharedTool.get(context, Constant.TOKEN, "") as String, id)
        initListener()
        if (info != null) {
            initDatas()
        }


    }

    private fun initDatas() {
        deviceType.text = listDeviceType[info.devType!!]
        district.text = info.cityName
        township.text = info.townName
        disasterName.text = info.disasterName
        disasterNum.text = info.disNo
        monitorNum.text = info.monitorNo
        deviceFac.text = info.devFactory
        deviceNum.text = info.devName
        village.text = info.installLocation
        lon_bind_1.text = info.installLongitude
        lat_bind_1.text = info.installLatitude
        installLoc.text = "${info.cityName}${info.townName}${info.installLocation}"
        installtime.text = info.installTime
        when (info.devStatus) {
            0 -> {
                state.text = "在线"
                state.setTextColor(Color.GREEN)
            }
            1 -> {
                state.text = "离线"
                state.setTextColor(Color.RED)
            }
        }
        val split = info.devImage?.split(",")
        selImageList.clear()
        split?.forEach {
            if (it.isNotEmpty()) {
                val imageItem = ImageItem()
                imageItem.name = it.substring(it.lastIndexOf("/") + 1)
                imageItem.path = "${Constant.fileUrl}${it}&type=3"
                imageItem.mimeType = it
                selImageList.add(imageItem)
            }
        }
        adapter.images = selImageList

        data.setOnClickListener {
            mPresenter.requestData(SharedTool.get(context, Constant.TOKEN, "") as String, info.devId!!)
//            mPresenter.requestData(SharedTool.get(context, Constant.TOKEN, "") as String, "7761ce04-fb6d-4bfd-9bac-9c50977d1b22")
        }
    }

    private fun initListener() {
        iv_back_toolbar.setOnClickListener {
            finish()
        }

        ll_right.setOnClickListener {

            val intent = Intent(context, EquipmentBindingActivity::class.java)
            intent.putExtra("bindInfo", info as Serializable)
            intent.putExtra("action", "update")
            startActivity(intent)
        }

    }

    override fun handlerBindRecordResult(t: BindRecordInfoBean) {
        deviceType.text = listDeviceType[t.data!!.devType!!]
        district.text = t.data?.cityName
        township.text = t.data?.townName
        disasterName.text = t.data?.disasterName
        disasterNum.text = t.data?.disNo
        monitorNum.text = t.data?.monitorNo
        deviceFac.text = t.data?.devFactory
        deviceNum.text = t.data?.devName
        when (t.data!!.devStatus) {
            0 -> {
                state.text = "在线"
                state.setTextColor(Color.GREEN)
            }
            1 -> {
                state.text = "离线"
                state.setTextColor(Color.RED)
            }
        }
        val split = t.data?.devImage?.split(",")
        selImageList.clear()
        split?.forEach {
            if (it.isNotEmpty()) {
                val imageItem = ImageItem()
                imageItem.name = it.substring(it.lastIndexOf("/") + 1)
                imageItem.path = "${Constant.fileUrl}${it}&type=3"
                imageItem.mimeType = it
                selImageList.add(imageItem)
            }
        }
        adapter.images = selImageList

    }

    /**
     * 初始化图片选择器
     */
    private fun initImagePicker() {
        val imagePicker = ImagePicker.getInstance()
        //设置图片加载器
        imagePicker.imageLoader = GlideImageLoader()
        //显示拍照按钮
        imagePicker.isShowCamera = true
        //允许裁剪（单选才有效）
        imagePicker.isCrop = false
        //是否按矩形区域保存
        imagePicker.isSaveRectangle = true
        //选中数量限制
        imagePicker.selectLimit = maxImgCount
        //多选
        imagePicker.isMultiMode = false

        adapter = ImagePickerNoAddAdapter(this, selImageList, maxImgCount)
        adapter.setOnItemClickListener(object : ImagePickerNoAddAdapter.OnRecyclerViewItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                //打开预览
                val intentPreview = Intent(context, ImagePreviewActivity::class.java)
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, adapter.getImages() as ArrayList<ImageItem>)
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
                startActivityForResult(intentPreview, REQ_CODE_PREVIEW)
            }
        })
        img_show.layoutManager = GridLayoutManager(this, 3)
        img_show.setHasFixedSize(true)
        img_show.adapter = adapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQ_CODE_PREVIEW) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS) as ArrayList<ImageItem>
                selImageList.clear()
                selImageList.addAll(images)
                adapter.images = selImageList
            }
        }
    }

    override fun showLoading() {

    }

    override fun hideLoading() {
    }

    override fun onError(msg: String, code: Int) {
        CustomToast.showToast(context, msg)
    }

    @SuppressLint("SetTextI18n", "InflateParams")
    private fun initTipsDialog(s: String) {
        val inflate = LayoutInflater.from(context).inflate(R.layout.dialog_tips, null)
        inflate.tips.text = "温馨提示"
        inflate.content.text = s
        val show = android.app.AlertDialog.Builder(context)
                .setView(inflate)
                .setCancelable(false)
                .show()
        inflate.cancels.setOnClickListener {
            show.dismiss()
        }
    }
}
